//
//  HomeTableViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/3/9.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {
    
    /// 保存请求数据模型数组
    var statusesModel: [Status]?{
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //如果没有登入,就设置未登入的界面
        if !userLogin {
            showVisionView?.stupViesionViewInfo(isHome: true, imageName: "visitordiscover_feed_image_house", title: "关注一些人,回这里看看有什么惊喜")
            return  //如果没有登入那我就不用设置导航栏上的按钮
        }
        print("access_token====",UserAccess.loadAccount()?.access_token ?? 0)
        //2.初始左右按钮
        setupNavi()
        
        //3.初始化中间标题按钮
        let titlBtu = TitleButton()
        titlBtu.setTitle("拖鞋 ", for: UIControlState.normal)
        titlBtu.addTarget(self, action: #selector(titleBtuOnClick(titleBtu:)), for: UIControlEvents.touchUpInside)
        navigationItem.titleView = titlBtu
        
        //4.监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(changeState(noti:)), name: NSNotification.Name(rawValue: XMGPopoverAnimatorWillShow), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(changeState(noti:)), name: NSNotification.Name.init(rawValue: XMGPopoverAnimatorWilldismiss), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(showPhotoBrowser(noti:)), name: NSNotification.Name(rawValue: pictureCollectionViewCellSelected), object: nil)
        
        //5添加下拉刷新控件 (默认没有值  nil)
        refreshControl = HomeRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadStatuesModel), for: UIControlEvents.valueChanged)
        
        
        
        //7.加载微博数据
        loadStatuesModel()
        
        //注册原创cell
        tableView.register(GWYHomeSatuesNormalTableViewCell.self, forCellReuseIdentifier: GWYHomeSatuesTableViewCellIdentifier.NormalCell.rawValue)
        //注册转发cell
        tableView.register(GWYForWardTableViewCell.self, forCellReuseIdentifier: GWYHomeSatuesTableViewCellIdentifier.ForwardCell.rawValue)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        //给cell一个预估高度
        //tableView.estimatedRowHeight = 200
        //让cell自己适应高度
        //tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    /**
     获取微博数据
     如果想调用一个私有的方法:
     1.去掉private
     2.@objc, 当做OC方法来处理
     */
    
    /// 记录当前的刷新状态
    var pullupRefreshFalg = false
    
    /// 加载微博数据
    func loadStatuesModel() ->Void {
        /*
         1.默认返回20条数据
         2.since_id 会返回比since_id大的微博
         3.max_id 会返回比max_id小的微博
         每条微博都有一个微博ID 而且为微博ID越后发 ID越大  递增
         新浪返回给我们的微博数据  是从大到小的返回给我们的
         */
        //1.默认当做是下拉处理
        var since_id = statusesModel?.first?.id ?? 0
        
        var max_id = 0
        //判断是是否是上拉加载
        if pullupRefreshFalg {
            since_id = 0 //把since_id设置成为0
            max_id = statusesModel?.last?.id ?? 0
        }
        
        Status.loadStatues(since_id: since_id, max_id: max_id) { (models, error) in
            //停止刷新
            self.refreshControl?.endRefreshing()
            if error == nil {
                
                //下拉刷新
                if since_id > 0 {
                    //1.如果是下拉刷新 ,就将获取的数据拼接在原来是数据前面
                    self.statusesModel = models! + self.statusesModel!
                    self.showNewStatuesCount(count: (models?.count)!)
                }else if max_id > 0 {
                    //上啦刷新  把获取到的诗句拼接到原有的数据后面
                    self.statusesModel = self.statusesModel! + models!
                }else {
                    self.statusesModel = models
                }
            }
        }
    }
    
    /// 设置微博刷新的提示
    ///
    /// - Parameter count: <#count description#>
    func showNewStatuesCount(count: Int) -> Void {
        //1.第一种方法
        //保存标签的frame
        self.newStatuesLable.text = count == 0 ? "没有新的微博可更新!" : "更新了\(count)新微博!";
        let rect = self.newStatuesLable.frame
        UIView.animate(withDuration: 2.0, animations: {
            //swift自动翻转动画  执行完动画之后自动移动化的形式回到之前的状态
            UIView.setAnimationRepeatAutoreverses(true)
            self.newStatuesLable.frame = rect.offsetBy(dx: 0, dy: rect.height*3)
        }) { (_) in
            self.newStatuesLable.frame = rect
        }
        
        
        //2.提示用户刷新了多少条微博
//        self.newStatuesLable.text = count == 0 ? "没有新的微博可更新!" : "更新了\(count)新微博!";
//        UIView.animate(withDuration: 1.0, animations: {
//            self.newStatuesLable.isHidden = false;
//            self.newStatuesLable.transform = CGAffineTransform.init(translationX: 0, y: 44);
//        })
//        //延迟两秒钟
//        UIView.animate(withDuration: 1.0, animations: { 
//            self.newStatuesLable.transform = CGAffineTransform.identity
//        }) { (_) in
//            self.newStatuesLable.isHidden = true
//        }
    }
    
    ///设置导航栏的方法
    func setupNavi() -> Void {
        //自定义UIBarButtonItem
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftItemOnClick(leftbtu:)))
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightItemOnClick(rightbtu:)))
    }
    
    /// 选中图片接受到通知 的执行方法
    ///
    /// - Parameter noti: <#noti description#>
    func showPhotoBrowser(noti: Notification) -> Void {
        
        //print(noti.userInfo ?? 9)
        //注意如果通过通知来传递值,一定要先判断值是否存在
        guard (noti.userInfo?[pictureCollectionViewCellIndexkey]) != nil else {
            print("当前选中图片index不存在!")
            return
        }
        
        guard noti.userInfo?[pictureCollectionViewCellURLSkey] != nil else {
            print("当前图片数组不存在!")
            return
        }
        let currentIndex = (noti.userInfo?[pictureCollectionViewCellIndexkey]) as! Int
        let pictureURLS = (noti.userInfo?[pictureCollectionViewCellURLSkey]) as! [URL]
        
        //1.创建图片显示控制器
        let photoBrowerVC = PhoteBrowerViewController(index: currentIndex, picURLS: pictureURLS)
        
        //2.model到控制器
        present(photoBrowerVC, animated: true, completion: nil)
    }
    
    //MARK:-BarButtonItem的点击事件
    func leftItemOnClick(leftbtu: UIBarButtonItem) -> Void {
        print(#function)
    }
    
    func rightItemOnClick(rightbtu: UIBarButtonItem) -> Void {
        print(#function)
        //跳转到二维码扫描界面
        let ORCstroyBoard = UIStoryboard.init(name: "ORCodeViewController", bundle: nil)
        let ORCVC = ORCstroyBoard.instantiateInitialViewController()
        present(ORCVC!, animated: true, completion: nil)
    }
    
    func titleBtuOnClick(titleBtu: UIButton) -> Void {
        //1.修改箭头方向
        //titleBtu.isSelected = !titleBtu.isSelected
        //2.弹出菜单
        //2.1创建一个控制器设置转成代理    默认情况下会移除以前控制器的View 换成新弹出控制器的view
        let sb = UIStoryboard.init(name: "PopoverViewController", bundle: nil)
        let popoverVC = sb.instantiateInitialViewController()
        
        //如果我们自定义的专场动画, 那么就不会移除以前控制器的view
        popoverVC?.transitioningDelegate = PopoverView;//设置model控制器的代理
        popoverVC?.modalPresentationStyle = UIModalPresentationStyle.custom //设置present的模式是自定义的模式
        present(popoverVC!, animated: true, completion: nil)
    }
    
    func changeState(noti: Notification) -> Void {
        print(#function)
        //在展开视图和消失视图的时候来更改按钮的选择状态
        let titltBtu = navigationItem.titleView as! TitleButton
        titltBtu.isSelected = !titltBtu.isSelected
    }
    
    //相当于OC中的dealoc方法
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //MARK: -- 懒加载  
    //因为delegate是弱应用  所以一定创建一个属性来保存这个值  不能直接创建赋值 这个样会发生一些错误
    private lazy var PopoverView: PopoverAnimate = {
        let Popoverdeleagte = PopoverAnimate()
        Popoverdeleagte.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350)
        return Popoverdeleagte
    }()
    
    /// 懒加载下拉刷新提醒微博
    private lazy var newStatuesLable:UILabel = {
        let tt = UILabel()
        tt.textColor = UIColor.white
        tt.backgroundColor = UIColor.orange;
        tt.textAlignment = NSTextAlignment.center
        tt.font = UIFont.systemFont(ofSize: 14)
        let height: CGFloat = 44
        tt.frame = CGRect.init(x: 0, y: -2*height, width: WIDTH, height: height)
        //把lable添加到导航栏上面
        self.navigationController?.navigationBar.insertSubview(tt, at: 0)
        return tt
    }()
    //缓存行高 
    
    /// 缓存行高的字典 key代表微博的唯一ID  value代表的cell的行高
    var rowHeightCaches:[Int: CGFloat] = [Int: CGFloat]();
}

extension HomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesModel?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = statusesModel?[indexPath.row]
        //1.获取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: GWYHomeSatuesTableViewCellIdentifier.cellID(model: model!)) as! GWYHomeSatuesTableViewCell
        
        //2.设置数据
        cell.modle = model
        
        //3.判断cell是否滑到最后一行
        let count = statusesModel?.count ?? 0
        
        if indexPath.row == count - 1 {
            pullupRefreshFalg = true //代表是下拉加载
            loadStatuesModel()
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        //1.取出数据模型
        let model = statusesModel?[indexPath.row]
        
        //2.首先从缓存中取出行高
        if let rowHeight = rowHeightCaches[(model?.id)!] {
            //print("从缓存中区行高")
            //返回缓存中的行高
            return rowHeight
        }
        //3.拿到cell (如果缓存中没有行高)
        let cell = tableView.dequeueReusableCell(withIdentifier: GWYHomeSatuesTableViewCellIdentifier.cellID(model: model!)) as! GWYHomeSatuesTableViewCell
        
        //4.计算cell的行高
        let height = cell.rowHeight(model: model!)
        
        //5.要把行高缓存起来
        rowHeightCaches[(model?.id)!] = height
        //print("重新计算");
        //6.返回cell的高度
        return height
    }
}





















